package fr.cephb.locustree.svg;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import fr.cephb.locustree.LTHistogram;
import fr.cephb.xml.SVG;


public class DefaultHistogramPainter
	implements HistogramPainter
	{
	private int histogram_height=100;

	
	
	public void setHeight(int histogramHeight)
		{
		histogram_height = histogramHeight;
		}
	
	public int getHeight()
		{
		return histogram_height;
		}
	
	public Element paint(Document dom,final LTHistogram histogram)
		{
		Element g1=null;
		//draw horizontal ticks
		if( histogram.getMaximum()>0)
			{
			g1=  dom.createElementNS(SVG.NS,"g");
			
			
			final int num_steps=10;
			double vert=Math.pow(10,Math.ceil(Math.log10(histogram.getMaximum())))/num_steps;
			if(vert>=10 && vert*3>=(histogram.getMaximum()))
				{
				vert/=10;
				}
			Element horizontal_axis= dom.createElementNS(SVG.NS,"g");
			horizontal_axis.setAttribute("style","stroke:lightgray;");
			g1.appendChild(horizontal_axis);
			double t=0;
			while(vert > 0 && t<= histogram.getMaximum())
				{
				
				double h= (t/histogram.getMaximum())*getHeight();
					
				
				h= getHeight()- h;
				Element h_axis= dom.createElementNS(SVG.NS,"line");
				//h_axis.setAttribute("title", String.valueOf(h));
				h_axis.setAttribute("x1", "0");
				h_axis.setAttribute("x2", String.valueOf(histogram.getWidth()));
				h_axis.setAttribute("y1", String.valueOf(h));
				h_axis.setAttribute("y2", String.valueOf(h));
				
				horizontal_axis.appendChild(h_axis);
				t+=vert;
				}
			
			Element histo= dom.createElementNS(SVG.NS,"g");
			histo.setAttribute("style","fill:url(#vgrad);stroke:black;");
			g1.appendChild(histo);
			for(int i=0;i< histogram.size();++i)
				{
				double h= (histogram.normalized(i))*getHeight();
				if(h>0)
					{
					Element rect= dom.createElementNS(SVG.NS,"rect");
					rect.setAttribute("title", String.valueOf(histogram.get(i)));
					rect.setAttribute("x", String.valueOf(i*histogram.getBarWidth()));
					rect.setAttribute("y", String.valueOf(getHeight()-h));
					rect.setAttribute("width", String.valueOf(histogram.getBarWidth()));
					rect.setAttribute("height", String.valueOf(h));
					histo.appendChild(rect);
					}
				}
			}
		return g1;
		}
	}
